<?php

namespace App\Http\Controllers\V1\Permission;

use App\Http\Requests\V1\PermissionRequest;
use App\Models\V1\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;

class PermissionsController extends Controller
{
    //
    //
    /**
     * 显示权限列表页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        return view('v1.permission.permissions');
    }

    /**
     * 获取权限数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的权限数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的权限数据
        $data = $this->getPermissionList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['display_name'] = $item['display_name'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['description'] = $item['description'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }


    /**
     * 进入单条用户数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['name'] = $request->input('name');
        $data['itemData'] = $this->getPermissionByCode($data['name']);
        Log::info('permission',$data);
        return view('v1.permission.permission_item', $data);
    }



    /**
     * 显示权限数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];
        return view('v1.form.upload_excel', $data);
    }

    /**
     * 删除权限基本信息
     *
     * @param PermissionRequest $request
     * @return array
     */
    public function deleteData(PermissionRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '权限代码[' . $request->input('name') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validatePermission($request);

            // 删除年级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '权限代码[' . $request->input('name') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除权限基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '权限批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 删除学期信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '权限批量删除成功！';
            }
        }

        return $response;
    }



    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的权限列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */

    private function getPermissionList($page = 1, $rows, $keywords) {
        if (!isset($keywords) || empty($keywords)) {
            $data = Permission::orderBy('updated_at', 'desc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = Permission::where('display_name', 'like', '%' . $keywords . '%')->orderBy('updated_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }


    /**
     * 根据权限代码获取对应权限信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getPermissionByCode($code)
    {
        $term = Permission::where('name', $code)->first();
        return $term;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新权限信息验证请求
     *
     * @param PermissionRequest $request
     */
    private function validatePermission(PermissionRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    /**
     * 处理删除权限信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {

        $where = $request->input('name');


        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = Permission::where('name', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = Permission::where('name', $where)->delete();
        }

        return $rspObj;
    }

}
